package org.javaymw.springboot.view;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.javaymw.springboot.dto.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/7/2 10:25
 */
public class ExcelView extends AbstractXlsView {

    private static final Logger logger = LoggerFactory.getLogger(ExcelView.class);

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {

        long start = System.currentTimeMillis();

        // change the file name
        response.setHeader("Content-Disposition", "attachment; filename=\"user-xls-file.xls\"");

        List<UserDto> userDtos = (List<UserDto>) model.get("users");

        if (userDtos != null && !userDtos.isEmpty()) {

            // create excel xls sheet
            Sheet sheet = workbook.createSheet("Area Detail");
            sheet.setDefaultColumnWidth(30);

            // create style for header cells
            CellStyle style = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontName("Arial");
            style.setFillForegroundColor(HSSFColor.BLUE.index);
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            font.setBold(true);
            font.setColor(HSSFColor.WHITE.index);
            style.setFont(font);


            // create header row
            Row header = sheet.createRow(0);
            header.createCell(0).setCellValue("userName");
            header.getCell(0).setCellStyle(style);
            header.createCell(1).setCellValue("passWord");
            header.getCell(1).setCellStyle(style);
            header.createCell(2).setCellValue("phone");
            header.getCell(2).setCellStyle(style);
            header.createCell(3).setCellValue("email");
            header.getCell(3).setCellStyle(style);

            int rowCount = 1;

            for (UserDto userDto : userDtos) {
                Row userRow = sheet.createRow(rowCount++);
                userRow.createCell(0).setCellValue(userDto.getUserName());
                userRow.createCell(1).setCellValue(userDto.getPassWord());
                userRow.createCell(2).setCellValue(userDto.getPhone());
                userRow.createCell(3).setCellValue(userDto.getEmail());
            }

        }

        long end = System.currentTimeMillis();

        logger.info("导出Excel耗时：" + (end - start) + " 毫秒.");
    }
}
